package com.kai.mqtt.message.service.impl;

import com.kai.mqtt.message.DupPublishMessage;
import com.kai.mqtt.message.service.IDupPublishMessageService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author weijk
 * @since 2024/6/10
 */
@Service
public class DupPublishMessageServiceImpl implements IDupPublishMessageService {

    private static final Map<String, Map<Integer, DupPublishMessage>> MAP = new ConcurrentHashMap<>();

    /**
     * 保存消息
     *
     * @param clientId          客户端 id
     * @param dupPublishMessage 消息
     */
    @Override
    public void put(String clientId, DupPublishMessage dupPublishMessage) {
        Map<Integer, DupPublishMessage> map = MAP.computeIfAbsent(clientId, (key) -> new ConcurrentHashMap<>());
        map.put(dupPublishMessage.getMessageId(), dupPublishMessage);
    }

    /**
     * 根据客户端 id 删除消息
     *
     * @param clientId 客户端 id
     */
    @Override
    public void remove(String clientId) {
        MAP.remove(clientId);
    }

    /**
     * 根据客户端 id 和消息 id 删除消息
     *
     * @param clientId  客户端 id
     * @param messageId 消息 id
     */
    @Override
    public void remove(String clientId, Integer messageId) {
        Map<Integer, DupPublishMessage> map = MAP.get(clientId);
        if (Objects.isNull(map)) {
            return;
        }

        map.remove(messageId);
        if (map.isEmpty()) {
            MAP.remove(clientId);
        }
    }

    /**
     * 根据客户端 id 获取消息列表
     *
     * @param clientId 客户端 id
     * @return 消息列表
     */
    @Override
    public List<DupPublishMessage> get(String clientId) {
        Map<Integer, DupPublishMessage> map = MAP.get(clientId);
        if (Objects.isNull(map)) {
            return new ArrayList<>();
        }

        return new ArrayList<>(map.values());
    }
}
